# frozen_string_literal: true

class Shell
  alias raw_exit exit

  def exe(command)
    puts "Shell: #{command}" if ENV['DEBUG']
    normal = system(command)
    exit Errors::ABNORMAL_RUNING_STATUS, "Shell 命令执行失败，程序提前退出：\n\n        #{command}\n" unless normal
  end

  def require(command)
    raise "未发现 #{command}，需要预先安装 #{command}"
  end

  def command?(command)
    system "which #{command}", out: File::NULL, err: File::NULL
  end

  def expand(path)
    File.expand_path(path)
  end

  def rc_append(*contents)
    content = "\n" + contents.join("\n") + "\n"
    File.write(expand('~/.zshrc'), content, mode: 'a')
  end

  def exit(status, message)
    if status == 0
      puts message
      raw_exit
    else
      $stdout.puts message
      raw_exit status
    end
  end

  module Errors
    COMMAND_NOT_FOUND = 201       # 一键脚本子命令不存在
    ABNORMAL_RUNING_STATUS = 202  # 执行 Shell 命令的状态码非零
    FILE_NOT_FOUND = 203          # 文件未找到
    BACKUP_FILE_EXIST = 204       # 备份文件已存在
  end
end

shell = Shell.new

define_method(:shell) { shell }
